//
//  GYModfyPhoneViewController.m
//  GoodLuck
//
//  Created by apple on 2018/5/11.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYModfyPhoneViewController.h"
#import "GYNetWorkTools.h"

@interface GYModfyPhoneViewController ()

@property (weak, nonatomic) IBOutlet UIButton *SMSBtu;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *SMSTF;
@property (weak, nonatomic) IBOutlet UIButton *subBtu;

/** 定时器 */
@property (nonatomic, strong) dispatch_source_t timer;
@end

@implementation GYModfyPhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化
    [self setupUI];
}

- (void)setupUI {
    self.SMSBtu.layer.cornerRadius = 4;
    self.subBtu.layer.cornerRadius = 4;
    
    if (self.isBindPhone) {
        self.navigationItem.title = @"绑定手机号";
    }else {
        self.phoneTF.text = self.member_mobile;
        self.navigationItem.title = @"解绑手机号";
    }
}

- (IBAction)getSMSCode:(UIButton *)sender {
    if (self.isBindPhone) {
        //代表绑定
        if ([self isMobileNumber:self.phoneTF.text]) {
            [GYNetWorkTools requestBindPhoneSMS:self.phoneTF.text success:^(NSDictionary *obj) {
                //NSLog(@"obj======%@",obj);
                int code = [[obj objectForKey:@"code"] intValue];
                if (code == 200) {
                    [EasyTextView showText:@"获取验证码成功!"];
                }else if(code == 400) {
                    NSDictionary *datas = [obj objectForKey:@"datas"];
                    NSLog(@"error=======%@",[datas objectForKey:@"error"]);
                    [EasyTextView showText:[datas objectForKey:@"error"]];
                }
                
            } error:^(NSError *error) {
                [EasyTextView showText:@"获取验证码失败!"];
                NSLog(@"error=======%@",error);
            }];
        }
    }else {
        //代表解绑
        if ([self isMobileNumber:self.phoneTF.text]) {
            [GYNetWorkTools requestDeletePhoneSMS:^(NSDictionary *obj) {
                //NSLog(@"obj========%@",obj);
                int code = [[obj objectForKey:@"code"] intValue];
                if (code == 200) {
                    [EasyTextView showText:@"获取验证码成功!"];
                }else if (code == 400){
                    NSDictionary *datas = [obj objectForKey:@"datas"];
                    NSLog(@"error=======%@",[datas objectForKey:@"error"]);
                    [EasyTextView showText:[datas objectForKey:@"error"]];
                }
                
            } error:^(NSError *error) {
                [EasyTextView showText:@"获取验证码失败!"];
                NSLog(@"error=======%@",error);
            }];
            
        }
    }
    //2.1.创建GCD定时器
    __block int count = 60;
    sender.enabled = NO;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
    
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(self.timer, ^{
        //2.2改变按钮文字
        count = count - 1;
        if (count <= 0) {
            self.timer = nil;
            dispatch_async(dispatch_get_main_queue(), ^{
                [sender setTitle:@"获取验证码" forState:UIControlStateNormal];
                sender.enabled = YES;
                
            });
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [sender setTitle:[NSString stringWithFormat:@"%d秒",count] forState:UIControlStateNormal];
            });
        }
    });
    dispatch_resume(self.timer);

}

- (IBAction)onClick:(UIButton *)sender {
    if (self.isBindPhone) {
        //绑定
        if ([self isMobileNumber:self.phoneTF.text]) {
            [GYNetWorkTools requestBindPhone:self.phoneTF.text success:^(NSDictionary *obj) {
                //NSLog(@"obj========%@",obj);
                int code = [[obj objectForKey:@"code"] intValue];
                if (code == 200) {
                    //发送强制登陆的通知 并且返回个人中心
                    [[NSNotificationCenter defaultCenter]postNotificationName:showLoginView object:nil];
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }else if(code == 400) {
                    NSDictionary *datas = [obj objectForKey:@"datas"];
                    [EasyTextView showText:[datas objectForKey:@"error"]];
                }
                
            } error:^(NSError *error) {
                [EasyTextView showText:@"绑定手机号失败,请重新绑定!"];
                NSLog(@"bindPhoneError =========%@",error);
            }];
        }
    }else {
        //解绑
        if (self.SMSTF.text.length == 0) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"请输入验证码!" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
        }else {
            [GYNetWorkTools requestDeletePhone:self.SMSTF.text success:^(NSDictionary *obj) {
                //NSLog(@"obj=======%@",obj);
                int code = [[obj objectForKey:@"code"] intValue];
                if (code == 200) {
                    GYModfyPhoneViewController *modfyPhone = [[GYModfyPhoneViewController alloc] initWithNibName:@"GYModfyPhoneViewController" bundle:nil];
                    modfyPhone.bindPhone = YES;
                    [self.navigationController pushViewController:modfyPhone animated:YES];
                }else if(code == 400) {
                    [EasyTextView showText:@"解绑手机号失败!"];
                }
            } error:^(NSError *error) {
                [EasyTextView showText:@"解绑手机号失败!"];
            }];
        }
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark--判断手机号码
- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    //    电信号段:133/153/180/181/189/177
    //    联通号段:130/131/132/155/156/185/186/145/176
    //    移动号段:134/135/136/137/138/139/150/151/152/157/158/159/182/183/184/187/188/147/178
    //    虚拟运营商:170
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    //     NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    NSString * CM = @" ^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    //     NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    NSString * CU =  @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    //     NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    NSString * CT = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

@end
